/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PlayerInitPanel.java
 *
 * Created on Jul 29, 2011, 1:51:33 PM
 */
package deatax.display.gui;

import deatax.network.ChangedListener;
import deatax.network.Client;
import deatax.network.ClientHandler;
import deatax.network.ConnectionListener;
import deatax.network.Messages;
import deatax.network.NetworkListener;
import deatax.network.Server;
import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;

/**
 *
 * @author pson
 */
public class HostInitPanel extends javax.swing.JPanel implements ConnectionListener, NetworkListener, ChangedListener {

    
    ArrayList<ClientHandler> clients;
    private int n;
    Server s = null;

    /** Creates new form PlayerInitPanel */
    public HostInitPanel() {
        initComponents();
        clients = new ArrayList<ClientHandler>();
    }

    public void open() {
        clients.clear();
        pnlPlayers.removeAll();
        n = 1;
        Client.get().addListener(this);
    }

    public void close() {
        if (s != null) {
            s.kill();
            s = null;
        }
        Client.get().removeListener(this);
        btnBroadcast.setEnabled(true);
    }

    public void assignPlayers() {
        ArrayList<String> args = new ArrayList<String>();
        for (Component c : pnlPlayers.getComponents()) {
            if (c instanceof PlayerCreatePanel) {
                PlayerCreatePanel pcp = (PlayerCreatePanel) c;
                //Client.get().getControl().addPlayer(pcp.getPlayerName(), pcp.getColor());
                args.add(pcp.getPlayerName());
                args.add(String.valueOf(pcp.getColor().getRGB()));
            }
        }
        Server.get().sendMessages(Messages.PLAYER_SET, args);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnBroadcast = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        pnlPlayers = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        portPanel = new deatax.display.gui.JLabeledTextField();

        btnBroadcast.setText("Broadcast");
        btnBroadcast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBroadcastActionPerformed(evt);
            }
        });

        pnlPlayers.setLayout(new javax.swing.BoxLayout(pnlPlayers, javax.swing.BoxLayout.Y_AXIS));
        jScrollPane1.setViewportView(pnlPlayers);

        jLabel1.setFont(jLabel1.getFont().deriveFont(jLabel1.getFont().getStyle() | java.awt.Font.BOLD, jLabel1.getFont().getSize()+9));
        jLabel1.setText("Host Game");

        portPanel.setText("9999");
        portPanel.setEmptyText("Port");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                    .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(portPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 129, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnBroadcast, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnBroadcast)
                    .add(portPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnBroadcastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBroadcastActionPerformed
        
        btnBroadcast.setEnabled(false);
        if (s != null) {
            s.kill();
            s.clear();
        }
        try {
            s = new Server(Integer.parseInt(portPanel.getText()));
            s.run();
            s.addConnectListener(this);
            Client.get().connect("localhost", Integer.parseInt(portPanel.getText()));
        } catch (Exception ex) {
        }
        validate();
    }//GEN-LAST:event_btnBroadcastActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBroadcast;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pnlPlayers;
    private deatax.display.gui.JLabeledTextField portPanel;
    // End of variables declaration//GEN-END:variables

    @Override
    public void onConnection(ClientHandler connection) {
        System.out.println("connection receive in host: " + connection);
        //Broadcast to existing clients that a new player has joined
        connection.sendMessage(Messages.CONNECT_DETAILS, new String[]{String.valueOf(n), String.valueOf(n - 1)});
        s.sendMessages(Messages.NEW_CLIENT, new String[]{String.valueOf(n)});
        for (Component c : pnlPlayers.getComponents()) {
            if (c instanceof PlayerCreatePanel) {
                PlayerCreatePanel pcp = (PlayerCreatePanel) c;
                s.sendMessages(Messages.CLIENT_NAME, new String[]{String.valueOf(pcp.getN()), pcp.getRawName(), String.valueOf(pcp.getColor().getRGB())});
            }
        }
        clients.add(connection);
        n++;
    }

    @Override
    public void processMessage(int type, String[] arg) {
        switch (type) {
            case Messages.NEW_CLIENT: {
                int pn = Integer.parseInt(arg[0]);
                PlayerCreatePanel pcp = new PlayerCreatePanel(pn);
                if (pn != 1) {
                    pcp.setEditable(false);
                } else {
                    pcp.addListener(this);
                }
                pnlPlayers.add(pcp);
                validate();
            }
            break;
            case Messages.CLIENT_NAME: {
                int pn = Integer.parseInt(arg[0]);
                String nc = arg[1];
                int pc = Integer.parseInt(arg[2]);
                PlayerCreatePanel pcp = (PlayerCreatePanel)pnlPlayers.getComponent(pn - 1);
                if (!pcp.getPlayerName().equals(nc)) {
                    pcp.setPlayerName(nc);
                }
                pcp.setColour(new Color(pc));
                validate();
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void changed(String name, Color color) {
        s.sendMessages(Messages.CLIENT_NAME, new String[]{"1", name, String.valueOf(color.getRGB())});
    }
}
